/*
 * @Author: szx
 * @Date: 2021-11-11 12:50:43
 * @LastEditTime: 2021-11-11 13:21:03
 * @Description:
 * @FilePath: \leetcode\800-899\844\844.cpp
 */
#include <iostream>
using namespace std;

class Solution {
   public:
    bool backspaceCompare(string s, string t) {
        int ps = s.size() - 1;
        int pt = t.size() - 1;
        int cs = 0, ct = 0;
        while (ps >= 0 || pt >= 0) {
            while (ps >= 0) {
                if (s[ps] == '#') {
                    cs++;
                    ps--;
                } else if (cs > 0) {
                    cs--;
                    ps--;
                } else {
                    break;
                }
            }
            while (pt >= 0) {
                if (t[pt] == '#') {
                    ct++;
                    pt--;
                } else if (ct > 0) {
                    ct--;
                    pt--;
                } else {
                    break;
                }
            }

            if (ps >= 0 && pt >= 0) {
                if (s[ps] != t[pt]) {
                    return false;
                }
            } else if (ps >= 0 || pt >= 0) {
                return false;
            }
            ps--;
            pt--;
        }
        return true;
    }
};